<template>
  <div class="container">
    <div class="header">
      <span class="project-title-font">{{ course?.courseName }}</span>
      <div>
        <a-button type="primary" @click="courseManagementModal = true"> <SettingOutlined /> 管理 </a-button>
      </div>
    </div>
    <a-spin :spinning="false">
      <div class="body">
        <div class="left-body">
          <!-- 课程基本信息 -->
          <div class="left-firstCard">
            <div class="left-firstCard-main">
              <div style="width: 25%">
                <span class="overview-info-font">课程任课教师</span>
                <div class="project-leader-list">
                  <div else v-for="user in teacherList" :key="user.userId">
                    <OverviewCard :message="user.userName" tips="教师" />
                  </div>
                </div>
              </div>
              <a-divider type="vertical" style="margin: 0px 10px; height: 100%" />
              <div style="width: 65%">
                <span class="overview-info-font">课程时间</span>
                <div class="project-time-box">
                  <OverviewCard
                    type="Date"
                    icon="CalendarOutlined"
                    :message="course?.createTime"
                    tips="创建时间"
                  />
                </div>
                <a-divider style="margin: 10px 0"></a-divider>

                <span class="overview-info-font">课程描述</span>

                <div style="margin-top: 10px; min-height: 30px">
                  {{ course?.courseDescription || course?.description || '暂无描述' }}
                </div>
              </div>
            </div>
          </div>
          <a-collapse
            class="left-card"
            :bordered="false"
            :forceRender="true"
            v-model:activeKey="activeKey"
          >
            <a-collapse-panel header="课程动态" key="1">
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  margin: 0 0 10px 0;
                "
              ></div>
            </a-collapse-panel>
          </a-collapse>
        </div>
        <div class="right-card">
          <div>
            <!-- 课程项目 -->
            <div>
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span class="overview-info-font">关联项目</span>
                <a-button size="small" @click="openAddProjectModal">
                  <template #icon>
                    <PlusOutlined />
                  </template>
                </a-button>
              </div>
              <a-divider style="margin: 5px 0"></a-divider>
              <a-list item-layout="horizontal" :data-source="projectList" class="courseList">
                <template #renderItem="{ item }">
                  <a-list-item>
                    <a> {{ item.projectName }}</a>
                  </a-list-item>
                </template>
              </a-list>
              <a-divider style="margin: 5px 0"></a-divider>
            </div>

            <!-- 任务统计 -->
            <div style="margin: 10px 0">
              <span class="overview-info-font">任务统计</span>
            </div>
            <div class="task-statistics">
              <a-spin :spinning="assignmentLoading">
                <a-row>
                  <a-col :span="8">
                    <a-statistic title="分配总数">
                      <template #formatter>
                        <span class="task-value">{{ assignment.total }}</span>
                      </template>
                    </a-statistic>
                  </a-col>
                  <a-col :span="8">
                    <a-statistic title="已完成">
                      <template #formatter>
                        <span class="task-value">{{ assignment.completed }}</span>
                      </template>
                    </a-statistic>
                  </a-col>
                  <a-col :span="8">
                    <a-statistic title="进行中">
                      <template #formatter>
                        <span class="task-value">{{ assignment.inProgress }}</span>
                      </template>
                    </a-statistic>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="8">
                    <a-statistic title="待领取">
                      <template #formatter>
                        <span class="task-value">{{ assignment.notStarted }}</span>
                      </template>
                    </a-statistic>
                  </a-col>
                  <a-col :span="8">
                    <a-statistic title="延期任务">
                      <template #formatter>
                        <span class="task-value">{{ assignment.extension }}</span>
                      </template>
                    </a-statistic>
                  </a-col>
                  <a-col :span="8">
                    <a-statistic title="待验收">
                      <template #formatter>
                        <span class="task-value">{{ assignment.notReviewed }}</span>
                      </template>
                    </a-statistic>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="8">
                    <a-statistic>
                      <template #title>
                        <span style="margin-left: 11px">完成率</span>
                        <a-tooltip placement="right">
                          <template #title>
                            <span>已完成任务/任务总数</span>
                          </template>
                          <question-circle-two-tone style="margin-left: 5px" />
                        </a-tooltip>
                      </template>
                      <template #formatter>
                        <span style="color: #73d897">
                          {{
                            assignment.total === 0
                              ? 0 + '%'
                              : ((assignment.completed / assignment.total) * 100).toFixed(1) + '%'
                          }}</span
                        >
                      </template>
                    </a-statistic>
                  </a-col>
                  <a-col :span="8">
                    <a-statistic>
                      <template #title>
                        <span style="margin-left: 11px">延期率</span>
                        <a-tooltip placement="right">
                          <template #title>
                            <span>延期未完成/任务总数</span>
                          </template>
                          <question-circle-two-tone style="margin-left: 5px" />
                        </a-tooltip>
                      </template>
                      <template #formatter>
                        <span style="color: #ff7575">
                          {{
                            assignment.total === 0
                              ? 0 + '%'
                              : ((assignment.extension / assignment.total) * 100).toFixed(1) + '%'
                          }}
                        </span>
                      </template>
                    </a-statistic>
                  </a-col>
                </a-row>
              </a-spin>
            </div>
          </div>
        </div>
      </div>
    </a-spin>
  </div>
  <!-- 课程管理窗口 -->
  <CourseManagementModal 
    v-model:modelVisible="courseManagementModal" 
    :course="course" 
    @confirm="findCourse"
  />
  <!-- 添加项目模态框 -->
  <a-modal
    v-model:visible="addProjectModalVisible"
    title="添加关联项目"
    @ok="handleAddProjects"
    @cancel="addProjectModalVisible = false"
    :confirmLoading="confirmLoading"
  >
    <a-alert
      v-if="selectedProjects.length === 0"
      message="请选择至少一个项目"
      type="warning"
      show-icon
      style="margin-bottom: 15px"
    />
    <a-transfer
      v-model:targetKeys="selectedProjects"
      :data-source="availableProjects"
      :titles="['可选项目', '已选项目']"
      :render="item => item.title"
      :disabled="confirmLoading"
      style="min-height: 300px"
    />
  </a-modal>
</template>

<script lang="ts" setup>
import { useStore } from 'vuex';
import TaskDao from '@/daos/task_dao';
import CourseDao from '@/daos/course_dao';
import ProjectDao from '@/daos/project_dao';
import { useRouter } from 'vue-router';
import { SettingOutlined, PlusOutlined, QuestionCircleTwoTone } from '@ant-design/icons-vue';
import CourseManagementModal from './courseManagementModal.vue';
import { message } from 'ant-design-vue';

const store = useStore();
const router = useRouter();
const taskDao = new TaskDao();
const courseDao = new CourseDao();
const projectDao = new ProjectDao();
const items = ref();

//课程管理窗口状态
const courseManagementModal = ref(false);

//项目折叠面板开关
const activeKey = ref([1, 2]);
//加载状态
const loading = ref(true);
//获取课程id
const courseId = store.getters.courseId;
//获取课程的项目列表
const projectList = store.getters.courseProjectList;
//获取课程的教师列表
const teacherList = store.getters.courseTeacherList;
//存储课程基本信息对象
const course = ref();
//查询课程基本信息
const findCourse = () => {
  courseDao
    .findCourse(courseId, null)
    .then((result) => {
      course.value = result.data.data[0];
      console.log(course.value);
    })
    .catch((error) => {});
};
//任务分配记录加载开关
const assignmentLoading = ref();
//任务分配信息
const assignment = ref({
  completed: 0,
  extension: 0,
  inProgress: 0,
  notReviewed: 0,
  notStarted: 0,
  total: 0
});
//查询任务的分配数量
const findAssignmentNumber = async () => {
  assignmentLoading.value = true;
  taskDao
    .findTaskAssignmentNumberByCourseId(courseId, 2)
    .then((result) => {
      assignment.value = result.data.data;
      assignmentLoading.value = false;
    })
    .catch((error) => {
      console.error('获取任务分配记录的数量错误,findAssignmentNumber', error);
      assignmentLoading.value = false;
    });
};

// 添加项目模态框相关
const addProjectModalVisible = ref(false);
const selectedProjects = ref<string[]>([]);
const availableProjects = ref<any[]>([]);
const confirmLoading = ref(false);

// 打开添加项目模态框
const openAddProjectModal = async () => {
  selectedProjects.value = [];
  confirmLoading.value = true;
  
  try {
    // 获取所有项目
    const result = await projectDao.findProjects(
      store.getters.userId,
      '',
      1, // 项目类型，1代表教学项目
      null, // 项目状态，不筛选
      null, // 日期范围，不筛选
      1, // 当前页
      100 // 每页数量
    );
    
    if (result.data.code === 200 && result.data.data) {
      const allProjects = result.data.data.rows || [];
      // 将已关联的项目ID过滤掉
      const currentProjectIds = projectList.map(item => item.projectId);
      
      // 转换为Transfer组件需要的格式
      availableProjects.value = allProjects
        .filter(project => !currentProjectIds.includes(project.projectId))
        .map(project => ({
          key: project.projectId.toString(),
          title: project.projectName,
          description: project.projectDescription,
          disabled: false
        }));
      
      addProjectModalVisible.value = true;
    } else {
      message.error('获取项目列表失败');
    }
  } catch (error) {
    console.error('获取项目列表失败', error);
    message.error('获取项目列表失败');
  } finally {
    confirmLoading.value = false;
  }
};

// 处理添加项目
const handleAddProjects = async () => {
  if (selectedProjects.value.length === 0) {
    message.warning('请选择至少一个项目');
    return;
  }
  
  confirmLoading.value = true;
  
  try {
    // 将选中的项目ID转换为数字数组
    const projectIds = selectedProjects.value.map(id => parseInt(id));
    
    // 调用添加项目API
    const result = await courseDao.addProjectsToCourse(courseId, projectIds);
    
    if (result.data.code === 200) {
      message.success('添加项目成功');
      // 刷新课程信息，包括关联的项目
      findCourse();
      addProjectModalVisible.value = false;
    } else {
      message.error(result.data.msg || '添加项目失败');
    }
  } catch (error) {
    console.error('添加项目失败', error);
    message.error('添加项目失败');
  } finally {
    confirmLoading.value = false;
  }
};

onMounted(() => {
  findAssignmentNumber();
  findCourse();
});
</script>

<style scoped lang="scss">
.container {
  background: #fafafa;
  display: flex;
  flex-direction: column;
  height: 100%;
  .header {
    height: 60px;
    min-height: 50px;
    min-width: 1080px;
    padding: 0 10px 0 30px;

    display: flex;
    justify-content: space-between;
    background: #fff;
    align-items: center;
    border: 1px;
    border-radius: 8px;
    box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);

    position: sticky; /* 使用 sticky 定位 */
    top: 0; /* 固定在顶部 */
    z-index: 1000; /* 确保 header 在最上层 */
    .project-title {
      font-size: 24px;
      margin-bottom: 20px;
    }

    .project-title-font {
      font-size: 20px;
      font-weight: 600;
      color: #333;
    }
  }

  .body {
    display: flex;
    background: #fafafa;
    padding: 15px;
    .left-body {
      height: 100%;
      width: 60%;
      min-width: 640px;
      display: flex;
      flex-direction: column;

      .left-firstCard {
        padding: 5px 0px;
        height: 40%;
        background-color: #fff;
        margin-bottom: 8px;
        border: 1px solid #eee;
        padding: 15px 15px 15px 24px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        .left-firstCard-main {
          height: 85%;
          display: flex;
          justify-content: space-around;
          margin-bottom: 15px;
        }
      }

      .left-card {
        max-height: 600px;
        height: 100%;
        padding: 5px 0px;
        background-color: #fff;
        margin-top: 8px;
        border: 1px solid #eee;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }

    .right-card {
      width: 39%;
      height: 100%;
      min-width: 400px;
      min-height: 580px;
      padding: 15px 15px 15px 24px;
      margin-left: 8px;
      background-color: #fff;
      border: 1px solid #eee;
      overflow-y: auto;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      .courseList {
        max-height: 180px;
        min-width: 300px;
        overflow-y: auto;
      }

      .task-statistics {
        width: 100%;
        margin: auto auto;
        text-align: center;
      }
    }
  }
}
.project-leader-list {
  display: flex;
  flex-direction: column;
  height: 80%;
  overflow-y: auto;
  margin-top: 10px;
}

.project-time-box {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
}

.project-created-info {
  font-size: 14px;
  color: #6666;
}

.overview-info-font {
  font-size: 14px;
  color: #6666;
}
.task-value:hover {
  cursor: pointer;
  color: #1677ff !important;
}
</style>
